<?php
namespace Modules\Admin\Controllers\Ucenter;

use S\Util\Ip;
use S\Request;
use Base\Controller\Action;
use Base\Exception\Controller as Exception;
use Modules\Admin\Model\Service\Access\Control as ServiceAccessControl;
use Modules\Admin\Model\Service\Access\Config as ServiceAccessConfig;
use Modules\Admin\Model\Dao\Api\Ldap as ApiLdap;
use Modules\Admin\Model\Data\Validate as DataValidate;

abstract class Controller extends Action {

    protected $sys_view = false; //是否使用系统的模板文件

    final public function init() {
        $this->_checkAccessIp();
        if (!in_array($this->getRequest()->getControllerName(), ServiceAccessConfig::$no_login_controller)) {
            $this->_checkAccessLoginUcenter();
            $this->_checkAuthorizationUcenter();
        }
    }

    /**
     * 页面渲染输出
     * @param $tpl_vars
     * @return bool
     */
    public function displayView($tpl_vars) {
        if ($this->sys_view) {
            //使用phplib下的模板文件
            $this->_view->setScriptPath(APPLICATION_BASE_TPL_PATH);
        }

        $this->buildMenu();

        $ext = \Yaf\Application::app()->getConfig()->get('yaf.view.ext');
        $tpl_path = strtolower($this->getRequest()->controller) . DIRECTORY_SEPARATOR . strtolower($this->getRequest()->action) . '.' . $ext;
        $this->_view->display($tpl_path, $tpl_vars);
    }

    public function getRenderView($tpl = null, array $response = array()) {
        if ($this->sys_view) {
            //使用phplib下的模板文件
            $this->_view->setScriptPath(APPLICATION_BASE_TPL_PATH);
        }

        if (!$tpl) {
            $ext = \Yaf\Application::app()->getConfig()->get('yaf.view.ext');
            $tpl = strtolower($this->getRequest()->getControllerName()) . DIRECTORY_SEPARATOR .
                strtolower($this->getRequest()->getActionName()) . "." . $ext;
        }
        \Yaf\Dispatcher::getInstance()->autoRender(false);
        $ret = $this->_view->render($tpl, $response);
        \Yaf\Dispatcher::getInstance()->autoRender(true);
        return $ret;
    }

    /**
     * 生成菜单并把变量抛向需要菜单有菜单的模版
     *
     * @return boolean|void
     */
    protected function buildMenu() {
        $menu = ServiceAccessControl::getNavMenu();
        $ext = \Yaf\Application::app()->getConfig()->get('yaf.view.ext');
        $menuview = $this->_view->render(APPLICATION_BASE_TPL_PATH . 'inc/menu_ucenter.' . $ext, array('menu' => $menu));
        $this->_view->assign('menuview', $menuview);
    }

    /**
     * 校验ip访问是否合法
     *
     * @throws Exception
     */
    private function _checkAccessIp() {
        if (!Ip::isPrivateIp(Ip::getClientIp()) && !in_array(Ip::getClientIp(), ServiceAccessConfig::getAllowIp())) {
            throw new Exception('error.admin.illegal_request');
        }
    }

    /**
     * 登录校验
     *
     * @return bool
     * @throws Exception
     */
    private function _checkAccessLoginUcenter() {
        $ticket = Request::session('ticket');
        if ($ticket){
            $user_info = (new ApiLdap())->validate($ticket, ApiLdap::IS_NOT_RETURN);
            return $user_info ?: true;
        }
        else {
            session_destroy();
            $error_config = \S\Config::confError('admin.sign_in_again');
            $msg = sprintf($error_config['msg'], APP_ADMIN_PATH);
            throw new Exception($msg, $error_config['retcode']);
        }
    }

    /**
     * 权限校验
     */
    private function _checkAuthorizationUcenter() {
        $controller = $this->getRequest()->controller;
        $action = $this->getRequest()->action;

        if ($_SESSION['isadmin'] || $controller == 'Welcome'){
            return true;
        }
        $controller_check = 'controller_'.strtolower($controller);
        $action_check = $action.'action';
        $menu_id = $_SESSION['actionlist'][$controller_check]['methods'][$action_check]['mid'];
        $current_action = strtolower($controller) . '_' . strtolower($action);

        if ($menu_id){
            return true;
        } else if (in_array($current_action,$_SESSION['permissionlist'])){
            return true;
        } else{
            $url = $_SERVER['HTTP_REFERER'] ?: APP_ADMIN_PATH . '/welcome/index';
            $error_config = \S\Config::confError('admin.can_not_access');
            $msg = sprintf($error_config['msg'], $controller, $action, $url);
            throw new Exception($msg, $error_config['retcode']);
        }
    }

}